<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\RoomFollow\Action\Sidebar;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Common\Middleware\SidebarAuthMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\RoomFollow\Contract\RoomFollowContract;
use MoChat\Plugin\RoomTrack\Constants\EventName;
use MoChat\Plugin\RoomTrack\Contract\RoomTrackContract;

/**
 * 修改跟进.
 *
 * Class Update
 * @Controller
 */
class Update extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var RoomFollowContract
     */
    protected $roomFollowService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * 互动轨迹表.
     * @Inject
     * @var RoomTrackContract
     */
    private $track;

    /**
     * @Middlewares({
     *     @Middleware(SidebarAuthMiddleware::class)
     * })
     * @RequestMapping(path="/sidebar/roomFollow/update", methods="PUT")
     */
    public function handle(): array
    {
        // 接收参数
        $params['trackId'] = (int) $this->request->input('trackId');
        $params['targetId'] = (int) $this->request->input('targetId');
        $params['content'] = $this->request->input('content');
        // 校验参数
        $this->validated($params);

        # # 数据操作
        Db::beginTransaction();
        try {
            # # 跟进详情
            $follow = $this->roomFollowService->getRoomFollowById($params['targetId'], ['follow_template_id']);
            # # 修改跟进
            $id = $this->roomFollowService->updateRoomFollowById($params['targetId'], ['content' => $params['content']]);
            # # 修改轨迹
            $jsonContact = [
                'title' => $follow['followTemplateId'] > 0 ? EventName::FOLLOW_TEMPLATE : EventName::FOLLOW,
                'content' => $params['content'],
            ];
            $this->track->updateRoomTrackById($params['trackId'], ['content' => Json::encode($jsonContact)]);
            Db::commit();
            return [$id];
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('%s [%s] %s', '编辑用户跟进状态失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, $e->getMessage()); // '活动创建失败'
        }
    }

    /**
     * @return string[] 规则
     */
    public function rules(): array
    {
        return [
            'trackId' => 'required|integer|min:1|bail',
            'content' => 'required',
            'targetId' => 'required',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    public function messages(): array
    {
        return [
            'trackId.required' => '轨迹id 必传',
            'content.required' => '跟进内容 必传',
            'targetId.required' => '待办id 必传',
        ];
    }
}
